#include "Capturer.h"

#include <QThread>

Capturer::Capturer(QObject *parent) :
    QObject(parent),
    capturer(NULL),
    shouldCapture(false)
{
}

Capturer::Capturer(int index) :
    QObject(),
    capturer(cvCaptureFromCAM(index)),
    shouldCapture(false)
{
//    cvSetCaptureProperty(capturer, CV_CAP_PROP_FRAME_WIDTH, 854);

//    cvSetCaptureProperty(capturer, CV_CAP_PROP_FRAME_HEIGHT, 480);

    cvSetCaptureProperty(capturer, CV_CAP_PROP_FRAME_WIDTH, 1280);

    cvSetCaptureProperty(capturer, CV_CAP_PROP_FRAME_HEIGHT, 720);
    connect(this, SIGNAL(start()), this, SLOT(capture()));
}

Capturer::Capturer(QString filename) :
    QObject(),
    capturer(cvCaptureFromFile(filename.toStdString().c_str())),
    shouldCapture(false)
{
}

Capturer* Capturer::createCameraCapturer(int index)
{
    Capturer* capturer = new Capturer(index);

    QThread* thread = new QThread();
    connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));

    capturer->moveToThread(thread);
    thread->start();

    return capturer;
}

void Capturer::startCapture()
{
    emit start();
}

void Capturer::capture()
{
    shouldCapture = true;
    while (shouldCapture) {
        this->captureNextFrame();
    }

}

void Capturer::captureNextFrame()
{
    currentFrame = cvQueryFrame(capturer);

    if (currentFrame == NULL) {
        qDebug("Error getting frame");
        shouldCapture = false;
        return;
    }

    IplImage* rgbFrame = cvCreateImage(cvSize(currentFrame->width, currentFrame->height), currentFrame->depth, currentFrame->nChannels);

    cvCvtColor(currentFrame, rgbFrame, CV_BGR2RGB);

    QImage image(rgbFrame->width, rgbFrame->height, QImage::Format_RGB888);

    if (image.isNull()) {
        cvReleaseImage(&rgbFrame);
        shouldCapture = false;
        return;
    }

    const uchar* bitsPtr = image.bits();
    memcpy((void*)bitsPtr, (const void*)rgbFrame->imageData, rgbFrame->imageSize);

    cvReleaseImage(&rgbFrame);

    emit capturedNewImage(image);
}
